import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { insertCartAPI, findNewCartListAPI, delCartAPI,  } from '@/apis/cart'
import {useUserStore} from './userStore'


 export const useCartStore = defineStore('cart',()=>{

   const updateNewList = async () => {
     const res = await findNewCartListAPI()
     cartList.value = res.result

   } 
  //定义state 
  const cartList = ref([])
   const userStore = useUserStore()
   const isLogin = computed(() => userStore.userInfo.token)
  // 定义action
  const addCart = async (goods)=>{
    const { skuId, count } = goods
    if(isLogin.value){
      // 登录之后的加入购车逻辑
      await insertCartAPI({ skuId, count })
      ElMessage.success('添加购物车成功')
      updateNewList()
    }else{
      // 添加购物车
      // 已添加果count++
      // 没添加果 直接push
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        // 找到了
        item.count = item.count + goods.count
        // item.count++
      } else {
        // 没找到
        cartList.value.push(goods)
      }
      ElMessage.success('添加购物车成功')

    }
    }
   
  const delCart = async (skuId)=>{

    if(isLogin.value){
      
      await delCartAPI([skuId])
      updateNewList()
    }else{
      // 思路1找到要删除的删除项的下标值  用splice
      //  const idx = cartList.value.findIndex((item)=> skuId === item.skuId)
      //  cartList.value.splice(idx,1)
      // 思路2用数组的过滤方法 filter
      const idx = cartList.value.filter((item) => skuId !== item.skuId)
      cartList.value = idx
    }

  }
   //  单选框状态逻辑、
const singleCheck = (skuId,selected)=>{
const item = cartList.value.find((item)=> item.skuId === skuId)
item.selected = selected
}

// 全选框状态逻辑
const allCheck = (selected)=>{
  cartList.value.forEach((item)=> item.selected = selected)

}
const isAll = computed(()=> cartList.value.every((item)=> item.selected))
  // 计算所有商品数量
  const allCount = computed(()=> cartList.value.reduce((sum, item)=> sum + item.count , 0))
  // 计算所有商品价格
   const allPrice = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0))

  //  已选择数量
   const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((sum, item) => sum + item.count, 0))
   // 4. 已选择商品价钱合计
   const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((sum, item) => sum + item.count * item.price, 0))
  
  
   const clearCart = ()=>{
    cartList.value = []
   }
  return{
    cartList,
    addCart,
    delCart,
    isAll,
    allCount,
    allPrice,
    singleCheck,
    allCheck,
    selectedCount,
    selectedPrice,
    updateNewList,
    clearCart
  }
 },
{
  persist:true
}
)